<template>
  <div id="ordersView">
    <empty-view
      v-if="ordersList.length === 0"
      description="您还没有任何订单，请购买商品后再来查看！"
    />
    <div v-else class="orders-main">
      <el-segmented
        v-model="value"
        :options="options"
        block
        style="position: sticky; top: 0; z-index: 100"
        @change="changeOption"
      />
      <empty-view
        v-show="selectOrdersList.length === 0"
        description="您还没有该选项的订单，请购买商品后再来查看！"
      />
      <div>
        <el-card
          v-for="item in selectOrdersList as OrdersFrontVO[]"
          :key="item.id"
          class="card-main"
          shadow="hover"
        >
          <div style="margin-bottom: 10px">
            <el-row :gutter="12">
              <el-col :span="12">
                <el-space>
                  <el-image
                    :preview-src-list="[item.businessAvatar || Img]"
                    :src="item.businessAvatar || Img"
                    fit="contain"
                    preview-teleported
                    style="
                      width: 25px;
                      height: 25px;
                      border-radius: 2px;
                      vertical-align: middle;
                    "
                  />
                  <el-text style="font-size: 18px" tag="b"
                    >{{ item.businessName }}
                  </el-text>
                  <el-button
                    size="small"
                    style="margin-left: 30px"
                    type="primary"
                    @click="toBusinessChat(item.businessId)"
                    >联系店铺
                  </el-button>
                  <el-button
                    size="small"
                    type="success"
                    @click="viewOrdersDetail(item)"
                    >查看详情
                  </el-button>
                </el-space>
              </el-col>

              <el-col :span="12" style="text-align: right">
                <el-text tag="b" type="danger"
                  >{{ getOrdersStatusLabel(item.status) }}
                </el-text>
              </el-col>
            </el-row>
          </div>
          <el-scrollbar max-height="150px">
            <el-row :gutter="12" style="margin: 0">
              <el-col
                v-for="ordersItem in item.ordersItems  as CartVO[]"
                :key="ordersItem.goodsId"
                :span="12"
              >
                <el-row style="margin: 5px 0">
                  <el-col :span="6">
                    <el-image
                      :preview-src-list="[ordersItem.goodsImage || Img]"
                      :src="ordersItem.goodsImage || Img"
                      fit="contain"
                      preview-teleported
                      style="
                        width: 80px;
                        height: 80px;
                        border-radius: 5px;
                        display: block;
                        margin: 0 auto;
                      "
                    />
                  </el-col>
                  <el-col :span="17" style="padding: 5px">
                    <el-space fill size="small">
                      <el-text :line-clamp="1" size="large" tag="b">
                        {{ ordersItem.goodsName }}
                      </el-text>
                      <el-text :line-clamp="1" size="small">
                        {{ ordersItem.goodsSpecName }}
                      </el-text>
                      <el-text>
                        <el-space>
                          <el-text
                            v-if="ordersItem.goodsScope < 1"
                            size="small"
                            tag="del"
                            >￥
                            {{ ordersItem.goodsPrice }}
                          </el-text>
                          <el-text size="small" type="danger">
                            到手价￥
                            <el-text size="large" type="danger">
                              {{
                                ordersItem.goodsScope < 1
                                  ? ordersItem.goodsScopePrice
                                  : ordersItem.goodsPrice
                              }}
                            </el-text>
                          </el-text>
                          <el-text size="small"
                            >数量x{{ ordersItem.goodsNum }}
                          </el-text>
                        </el-space>
                      </el-text>
                    </el-space>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-card>
      </div>
    </div>
    <!-- 订单详情弹窗-->
    <el-dialog
      v-model="ordersDetailVisible"
      :show-close="false"
      append-to-body
      center
      destroy-on-close
      title="订单详情"
      width="60%"
    >
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <el-descriptions :column="2" border class="margin-top">
          <el-descriptions-item align="center" label="订单编号">
            {{ selectOrders.id }}
          </el-descriptions-item>
          <el-descriptions-item align="center" label="支付金额">
            <el-text size="small" type="danger"
              >￥
              <el-text size="large" tag="b" type="danger">
                {{ selectOrders.payPrice }}
              </el-text>
            </el-text>
          </el-descriptions-item>
          <el-descriptions-item align="center" label="下单时间">
            {{ selectOrders.createTime }}
          </el-descriptions-item>

          <el-descriptions-item align="center" label="支付时间">
            {{ selectOrders.payTime }}
          </el-descriptions-item>

          <el-descriptions-item align="center" label="支付方式">
            <el-tag type="primary">支付宝</el-tag>
          </el-descriptions-item>
          <el-descriptions-item align="center" label="当前状态">
            <el-text tag="b"
              >{{ getOrdersStatusLabel(selectOrders.status) }}
            </el-text>
          </el-descriptions-item>
          <el-descriptions-item label="收货信息" label-align="center">
            <address-select
              @put-address="putAddress"
              showDetail
              :address-id="selectAddressId"
              confirm
              :update="selectOrders.status <= OrdersStatusEnum.DFH"
            />
          </el-descriptions-item>
        </el-descriptions>

        <el-row :gutter="12" style="margin: 10px 0">
          <el-col
            v-for="ordersItem in selectOrders.ordersItems  as CartVO[]"
            :key="ordersItem.goodsId"
            :span="12"
          >
            <el-row style="margin: 5px 0">
              <el-col :span="6">
                <el-image
                  :preview-src-list="[ordersItem.goodsImage || Img]"
                  :src="ordersItem.goodsImage || Img"
                  fit="contain"
                  preview-teleported
                  style="
                    width: 80px;
                    height: 80px;
                    border-radius: 5px;
                    display: block;
                    margin: 0 auto;
                  "
                />
              </el-col>
              <el-col :span="17" style="padding: 5px">
                <el-space fill size="small">
                  <el-text :line-clamp="1" size="large" tag="b">
                    {{ ordersItem.goodsName }}
                  </el-text>
                  <el-text :line-clamp="1" size="small">
                    {{ ordersItem.goodsSpecName }}
                  </el-text>
                  <el-text>
                    <el-space>
                      <el-text
                        v-if="ordersItem.goodsScope < 1"
                        size="small"
                        tag="del"
                        >￥
                        {{ ordersItem.goodsPrice }}
                      </el-text>
                      <el-text size="small" type="danger">
                        到手价￥
                        <el-text size="large" type="danger">
                          {{
                            ordersItem.goodsScope < 1
                              ? ordersItem.goodsScopePrice
                              : ordersItem.goodsPrice
                          }}
                        </el-text>
                      </el-text>
                      <el-text size="small"
                        >数量x{{ ordersItem.goodsNum }}
                      </el-text>
                      <el-tooltip content="申请退款" placement="top">
                        <el-button
                          size="small"
                          circle
                          type="danger"
                          @click="
                            handelOutPrice(selectOrders.id, ordersItem.id)
                          "
                          >退
                        </el-button>
                      </el-tooltip>
                    </el-space>
                  </el-text>
                </el-space>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button
            v-if="selectOrders.status === OrdersStatusEnum.DFK"
            size="small"
            type="success"
            @click="toPay"
            >去支付
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click="toBusinessChat(selectOrders.businessId)"
            >联系店家
          </el-button>
          <el-button size="small" @click="ordersDetailVisible = false"
            >关 闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import Img from "@/assets/logo.png";
import {
  AddressVO,
  CartVO,
  OrdersControllerService,
  OrdersFrontVO,
} from "@/api";
import EmptyView from "@/components/EmptyView.vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getOrdersStatusLabel,
  OrdersOption,
  OrdersStatusEnum,
} from "@/types/OrdersStatusEnum";
import AddressSelect from "@/components/AddressSelect.vue";

const value = ref(-1);

const options = OrdersOption;

//选项切换
function changeOption(val: number) {
  if (ordersList.value.length === 0) return;
  if (val !== -1) {
    selectOrdersList.value = ordersList.value.filter(
      (item) => item.status === val
    );
    return;
  }
  selectOrdersList.value = ordersList.value;
}

const ordersDetailVisible = ref(false);

//查看详情

const selectOrders = ref<OrdersFrontVO>({});
const selectAddressId = ref(""); //选择的地址Id

function viewOrdersDetail(row: OrdersFrontVO) {
  ordersDetailVisible.value = true;
  selectOrders.value = row;
  selectAddressId.value = selectOrders.value.address.id;
}

function putAddress(id: string) {}

function concatAddress(data: AddressVO) {
  return `${data.contact}，${data.phone}，${data.areaAddress}${data.detailAddress}`;
}

// 获取订单信息
const ordersList = ref<OrdersFrontVO[]>([]); //原始数据
const selectOrdersList = ref<OrdersFrontVO[]>([]); //选中的数据
function getOrdersInfo() {
  OrdersControllerService.getOrdersByUseUsingGet().then((res) => {
    ordersList.value = res.data || [];
    selectOrdersList.value = [...ordersList.value];
  });
}

getOrdersInfo();

//路由跳转
const router = useRouter();

// 联系店家
function toBusinessChat(businessId: number) {
  // 转换路由为标准化路径
  const path = router.resolve({
    path: "/chat",
    query: {
      businessId: businessId,
    },
  });
  window.open(path.href);
}

// 支付订单
function toPay() {
  if (!selectOrders.value.payNo) {
    ElMessage.warning("没有订单支付数据，无法结算！");
    return;
  }
  const subject =
    selectOrders.value.ordersItems![0].goodsName!.substring(0, 20) +
    "...等多件";
  OrdersControllerService.getOrdersInfoByPayNoUsingPut(
    selectOrders.value.payNo,
    subject
  ).then((res) => {
    router.push({
      path: "/pay_form",
      query: {
        form: res.data,
      },
    });
  });
}

// 申请退款
function handelOutPrice(ordersId, ordersItemId: any) {
  ElMessageBox.prompt("请输入您的退款理由！", "申请退款", {
    type: "info",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/,
    inputErrorMessage: "请输入退款理由！",
  })
    .then(({ value }) => {
      ElMessage({
        type: "success",
        message: `Your email is:${value}`,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Input canceled",
      });
    });
}
</script>

<style lang="scss" scoped>
#ordersView {
  margin-top: 75px;
  position: absolute;
  width: 80%;

  .orders-main {
    margin: 0 auto;
    width: 80%;

    .card-main {
      margin: 20px auto;
      display: flex;
      flex-direction: column;

      .card-title {
        padding: 10px 20px;
        font-weight: bolder;
        height: 20px;
        background-color: #d9ecff;
      }

      .card-content {
        flex: 1;
        padding: 20px;
      }
    }

    :deep(.el-card__body) {
      //padding: 5px;
    }
  }
}
</style>
